﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;

namespace DeepZoom.Behaviors
{
    internal class DeepZoomBounds
    {
        public static bool CheckBounds(MultiScaleImage msi)
        {
            Point ltPoint = msi.ViewportOrigin;
            Point rbPoint = msi.ElementToLogicalPoint(new Point(msi.ActualWidth, msi.ActualHeight));


            bool align = false;
            Point oPoint = new Point(ltPoint.X, ltPoint.Y);
            if (ltPoint.X < 0 && rbPoint.X < 1)
            {
                align = true;
                if (-ltPoint.X < 1 - rbPoint.X)
                    oPoint.X = 0;
                else
                    oPoint.X += 1 - rbPoint.X;
            }
            else if (ltPoint.X > 0 && rbPoint.X > 1)
            {
                align = true;
                if (ltPoint.X < rbPoint.X - 1)
                    oPoint.X = 0;
                else
                    oPoint.X += 1 - rbPoint.X;
            }

            double ratio = 1 / msi.AspectRatio;
            if (ltPoint.Y < 0 && rbPoint.Y < ratio)
            {
                align = true;
                if (-ltPoint.Y < ratio - rbPoint.Y)
                    oPoint.Y = 0;
                else
                    oPoint.Y += ratio - rbPoint.Y;
            }
            else if (ltPoint.Y > 0 && rbPoint.Y > ratio)
            {
                align = true;
                if (ltPoint.Y < rbPoint.Y - ratio)
                    oPoint.Y = 0;
                else
                    oPoint.Y += ratio - rbPoint.Y;
            }

            if (align)
            {
                msi.UseSprings = true;
                msi.ViewportOrigin = oPoint;
            }

            return align;
        }

        public static bool PointInRange(Point logicPoint, MultiScaleImage msi)
        {
            return logicPoint.X >= 0.0 && logicPoint.X <= 1.0 && logicPoint.Y >= 0.0 && logicPoint.Y <= (1 / msi.AspectRatio);
        }

    }
}
